<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\Request;
use think\Lang;

//error_reporting(E_ERROR | E_WARNING | E_PARSE);

$_root = rtrim(dirname(rtrim($_SERVER['SCRIPT_NAME'], '/')), '/');
define('__ROOT__', (($_root == '/' || $_root == '\\') ? '' : $_root));
define('__PUBLIC__', ROOT_PATH . 'public' . DS);
define('__UPLOADS__', __PUBLIC__ . 'uploads'. DS);
define('__IMAGE__', __UPLOADS__ . 'image'. DS);
// 应用公共文件

/**
 * 验证提交
 * @param $msg
 * @param string $status
 * @return \think\response\Json
 */
function ajax_info($msg, $status = '', $url = '')
{
    $data['info'] = $msg;
    $status ? $data['status'] = $status : '';
    $url ? $data['url'] = $url : '';
    return json($data);
}

function ajaxMsg($status = 1, $msg = '')
{
    header('Content-Type:application/json; charset=utf-8');
    $data['status'] = $status;
    $data['msg'] = $msg;
    exit(json_encode($data));
}

/**
 * 截取字符串
 *  GBsubstr(截断的字符串 , 开始的位置, 截取多少字)
 * @param  string $string
 * @param  int $start
 * @param  int|null $length
 * @return string
 * 
 */
function GBsubstr($string, $start, $length = null)
{
    /**
     *$str，需要截断的字符串 
     *$start，截断开始处，起始处为0 
     *$length，要截取的字数 
     *$encoding，网页编码，如utf-8,GB2312,GBK
     */
    return mb_substr($string, $start, $length, 'UTF-8');
}

/**
 * 导航面包屑
 */
function getCatpos($catid,$code ='')
{
    $str = cache($catid . 'getCatpos' . cookie('think_var'));
    if (empty($str1)) {
        $str = '';
        $list = db('nav')->field('id,pid,name,model,link')->select();
        $list = getParents($list, $catid);
        foreach ($list as $v) {
            $class = '';
            if (!empty($v['link'])) {
                if (stripos($v['link'], "http") === 0) {
                    $v['link'] = $v['link'];
                } else {
                    $d = $v['link'];
                    $dd = explode('-', $d);
                    $ddd = json_encode($dd);
                    $dddd = json_decode($ddd);
                    $v['link'] = url($dddd[0] . '/index', ['navid' => $dddd[1]],'html',Request::instance()->domain());
                }
            } else {
                $v['link'] = url($v['model'] . '/index', ['navid' => $v['id']],'html',Request::instance()->domain());
            }
            if ($v['pid'] == '0') {
                $class = 'class=\'loaid ' . $v['id'] . '\'';
            }
            $str .= '<a ' . $class . ' title=\'' . $v['name'] . '\' href=\'' . $v['link'] . '\'>' . $v['name'] .$code. '</a>';
        }
        cache($catid . 'getCatpos' . cookie('think_var'), $str);
    }

    //$str = '<a title="' . Lang::get('home') . '" href="/' . Request::instance()->module() . '">' . Lang::get('home') . '></a>' . $str;
    $str = '<a title="' . Lang::get('home') . '" href="' . Request::instance()->domain() . '">' . Lang::get('home') . $code.'</a>' . $str;
    return $str;
}

//获取某个分类的所有父分类
function getParents($categorys, $catid)
{
    $tree = [];
    foreach ($categorys as $item) {
        if ($item['id'] == $catid) {
            if ($item['pid'] > 0) {
                $tree = array_merge($tree, getParents($categorys, $item['pid']));
            }
            $tree[] = $item;
            break;
        }
    }
    return $tree;
}

/**
 * 供应、采购
 * @param $status
 * @return string
 */
function show_status($status)
{
    $controller = Request::instance()->controller();
    switch ($status) {
        case 0:
            $result = "<a class='label label-defalut radius'>" . Lang::get('Pending review') . "</a>";
            break;
        case 1:
            $result = "<a  class='label label-success radius'>" . Lang::get('Audited') . "</a>";
            break;
        case 2:
            $result = "<a class='label label-danger radius'>" . Lang::get('Fail') . "</a>";
            break;

        default:
            $result = "";
            break;
    }
    return $result;
}

/**阅读状态
 * @param $int
 * @return string
 *
 */
function read_status($int)
{
    switch ($int) {
        case 0:
            $result = "<a class='label label-defalut radius'>未读</a>";
            break;
        case 1:
            $result = "<a  class='label label-success radius'>已读</a>";
            break;
        case 2:
            $result = "<a class='label label-danger radius'>已回复</a>";
            break;
        default:
            $result = "";
            break;
    }
    return $result;
}

/**
 * 访客来源
 * @param $search_url
 * @return array
 */
function keytype($search_url)
{
    $config = array(
        '谷歌' => array("domain" => "www.google.", "kw" => "q", "charset" => "utf-8", 'type' => 0),
        '百度' => array("domain" => "www.baidu.", "kw" => "wd", "charset" => "gbk", 'type' => 1),
        '搜搜' => array("domain" => "soso.", "kw" => "query", "charset" => "gbk", 'type' => 2),
        '雅虎' => array("domain" => "yahoo.", "kw" => "q", "charset" => "utf-8", 'type' => 3),
        '必应' => array("domain" => "bing.", "kw" => "q", "charset" => "utf-8", 'type' => 4),
        '搜狗' => array("domain" => "sogou.", "kw" => "query", "charset" => "gbk", 'type' => 5),
        '有道' => array("domain" => "youdao.", "kw" => "q", "charset" => "utf-8", 'type' => 6),
        '360搜索' => array("domain" => "so.360.", "kw" => "q", "charset" => "utf-8", 'type' => 7)
    );
    $arr_key = array();
    foreach ($config as $key => $item) {
        $sh = preg_match("/\b{$item['domain']}\b/", $search_url);
        if ($sh) {
            $query = $item['kw'] . "=";
            $s_s_keyword = get_keyword($search_url, $query);
            $F_Skey = urldecode($s_s_keyword);
            $agwe = 0;
            if ($key == '百度') {
                $agwe = get_keyword($search_url, 'ie=');
                $item['charset'] = $agwe == '' ? $item['charset'] : $agwe;
            }
            if ($item['charset'] != "utf-8" && (!is_utf8($F_Skey) || $agwe)) {
                $F_Skey = iconv("gb2312//IGNORE", "UTF-8", $F_Skey);
            }
            $arr_key[0] = $F_Skey;
            $arr_key[2] = $item['type'];
            $arr_key[1] = $key;
        }
    }
    return $arr_key;
}

function is_utf8($word)
{
    if (preg_match("/^([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){1}/", $word) == true || preg_match("/([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){1}$/", $word) == true || preg_match("/([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){2,}/", $word) == true) {
        return true;
    } else {
        return false;
    }
}

function get_keyword($url, $kw_start)
{
    $start = stripos($url, $kw_start);
    if ($start) {
        $url = substr($url, $start + strlen($kw_start));
        $start = stripos($url, '&');
        if ($start > 0) {
            if ($start > 0) {
                $start = stripos($url, '&');
                $s_s_keyword = substr($url, 0, $start);
            } else {
                $s_s_keyword = substr($url, 0);
            }
        } else {
            $s_s_keyword = '';
        }
    } else {
        $s_s_keyword = '';
    }
    return $s_s_keyword;
}


/**
 * 获取浏览器版本
 * @return string 浏览器
 */
function getbrowser()
{
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        return '';
    }
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $brower = array(
        'MSIE' => 1,
        'Firefox' => 2,
        'QQBrowser' => 3,
        'QQ/' => 3,
        'UCBrowser' => 4,
        'MicroMessenger' => 9,
        'Edge' => 5,
        'Chrome' => 6,
        'Opera' => 7,
        'OPR' => 7,
        'Safari' => 8,
        'Trident/' => 1
    );
    $system = array(
        'Windows Phone' => 4,
        'Windows' => 1,
        'Android' => 2,
        'iPhone' => 3,
        'iPad' => 5
    );
    $browser_num = 0;//未知
    $system_num = 0;//未知
    foreach ($brower as $bro => $val) {
        if (stripos($agent, $bro) !== false) {
            $browser_num = $bro;
            break;
        }
    }
    foreach ($system as $sys => $val) {
        if (stripos($agent, $sys) !== false) {
            $system_num = $sys;
            break;
        }
    }

    return array('sys' => $system_num, 'bro' => $browser_num);

}

if (!function_exists('allow_release_arctype')) {
    /**
     * 允许发布文档的栏目列表
     */
    function allow_release_arctype($selected = 0, $allow_release_channel = array(), $lang=null,$selectform = true)
    {
        $where = [];
        if($lang){
            $where['c.lang'] = $lang; // 多语言
        }else{
            $where['c.lang'] = \request()->module() == 'admin' ? cookie('think_var_admin') : cookie('think_var'); // 多语言
        }

        if (!is_array($selected)) {
            $selected = [$selected];
        }
        $cacheKey = json_encode($selected) . json_encode($allow_release_channel).$lang . $selectform . json_encode($where);
        $select_html = cache($cacheKey);
//        $select_html=null;
        if (empty($select_html)) {
            /*允许发布文档的模型*/
            $allow_release_channel = !empty($allow_release_channel) ? $allow_release_channel : config('global.allow_release_channel');

            /*所有栏目分类*/
            // $arctype_max_level = intval(config('global.arctype_max_level'));
            $arctype_max_level = 3;
            $where['c.status'] = 1;
//            $fields = "c.id, c.pid, c.current_channel, c.typename, c.grade, count(s.id) as has_children, '' as children";
            $fields = "c.id, c.pid, c.lang,c.name,c.model,c.channeltype,c.grade, c.pids,count(s.id) as has_children, '' as children";

            $res = db('nav')
                ->field($fields)
                ->alias('c')
                ->join('__NAV__ s', 's.pid = c.id', 'LEFT')
                ->where($where)
                ->group('c.id')
                ->order('c.pid asc, c.sort asc, c.id')
                ->select();

            /*--end*/
            if (empty($res)) {
                return '';
            }
//dump($res);
//            exit();
            /*过滤掉第三级栏目属于不允许发布的模型下*/
            foreach ($res as $key => $val) {
//                if ($val['grade'] == ($arctype_max_level - 1) && !in_array($val['model'], $allow_release_channel)) {
//                    unset($res[$key]);
//                }

                if ($val['grade'] == ($arctype_max_level - 1) && !in_array($val['model'], $allow_release_channel)) {
                    unset($res[$key]);
                }

//                if ( !in_array($val['channeltype'], $allow_release_channel)) {
//                    unset($res[$key]);
//                }
            }

//            dump($res);
//            exit();
            /*--end*/

            /*所有栏目列表进行层次归类*/
            $arr = group_same_key($res, 'pid');

            for ($i = 0; $i < $arctype_max_level; $i++) {
                foreach ($arr as $key => $val) {
                    foreach ($arr[$key] as $key2 => $val2) {
                        if (!isset($arr[$val2['id']])) {
                            $arr[$key][$key2]['has_children'] = 0;
                            continue;
                        }
                        $val2['children'] = $arr[$val2['id']];
                        $arr[$key][$key2] = $val2;
                    }
                }
            }
            /*--end*/

//dump($arr);
//exit();
            /*过滤掉第二级不包含允许发布模型的栏目*/
            $nowArr = $arr[0];
            foreach ($nowArr as $key => $val) {
                if (!empty($nowArr[$key]['children'])) {
                    foreach ($nowArr[$key]['children'] as $key2 => $val2) {
                        if (empty($val2['children']) && !in_array($val2['model'], $allow_release_channel)) {
                            unset($nowArr[$key]['children'][$key2]);
                        }
                    }
                }
                if (empty($nowArr[$key]['children']) && !in_array($nowArr[$key]['model'], $allow_release_channel)) {
                    unset($nowArr[$key]);
                    continue;
                }
            }
            /*--end*/

//dump($nowArr);
//exit();
            /*组装成层级下拉列表框*/
            $select_html = '';
            if (false == $selectform) {
                $select_html = $nowArr;
            } else if (true == $selectform) {
                foreach ($nowArr AS $key => $val) {
                    $select_html .= '<option value="' . $val['id'] . '" data-grade="' . $val['grade'] . '" data-current_channel="' . $val['model'] . '"';
                    $select_html .= (in_array($val['id'], $selected)) ? ' selected="ture"' : '';
                    if (!empty($allow_release_channel) && !in_array($val['model'], $allow_release_channel)) {
                        $select_html .= ' disabled="true" style="background-color:#f5f5f5;"';
                    }
                    $select_html .= '>';
                    if ($val['grade'] > 0) {
                        $select_html .= str_repeat('&nbsp;', $val['grade'] * 4);
                    }
                    $select_html .= htmlspecialchars(addslashes($val['name'])) . '</option>';

                    if (empty($val['children'])) {
                        continue;
                    }
                    foreach ($nowArr[$key]['children'] as $key2 => $val2) {
                        $select_html .= '<option value="' . $val2['id'] . '" data-grade="' . $val2['grade'] . '" data-current_channel="' . $val2['model'] . '"';
                        $select_html .= (in_array($val2['id'], $selected)) ? ' selected="ture"' : '';
                        if (!empty($allow_release_channel) && !in_array($val2['model'], $allow_release_channel)) {
                            $select_html .= ' disabled="true" style="background-color:#f5f5f5;"';
                        }
                        $select_html .= '>';
                        if ($val2['grade'] > 0) {
                            $select_html .= str_repeat('&nbsp;', $val2['grade'] * 4);
                        }
                        $select_html .= htmlspecialchars(addslashes($val2['name'])) . '</option>';

                        if (empty($val2['children'])) {
                            continue;
                        }
                        foreach ($nowArr[$key]['children'][$key2]['children'] as $key3 => $val3) {
                            $select_html .= '<option value="' . $val3['id'] . '" data-grade="' . $val3['grade'] . '" data-current_channel="' . $val3['model'] . '"';
                            $select_html .= (in_array($val3['id'], $selected)) ? ' selected="ture"' : '';
                            if (!empty($allow_release_channel) && !in_array($val3['model'], $allow_release_channel)) {
                                $select_html .= ' disabled="true" style="background-color:#f5f5f5;"';
                            }
                            $select_html .= '>';
                            if ($val3['grade'] > 0) {
                                $select_html .= str_repeat('&nbsp;', $val3['grade'] * 4);
                            }
                            $select_html .= htmlspecialchars(addslashes($val3['name'])) . '</option>';
                        }
                    }
                }

            }
            cache($cacheKey, $select_html, null, 'admin_archives_release');
        }

        return $select_html;
    }
}

if (!function_exists('allow_release_arctype_index')) {
    /**
     * 前台导航 不知道可用否
     */
    function allow_release_arctype_index($selected = 0, $allow_release_channel = array(), $selectform = true)
    {
        $where = [];
        $where['c.lang'] = \request()->module() == 'admin' ? cookie('think_var_admin') : cookie('think_var'); // 多语言

        if (!is_array($selected)) {
            $selected = [$selected];
        }
        $cacheKey = json_encode($selected) . $selectform . json_encode($where);
        $select_html = cache($cacheKey);
        $select_html = null;
        if (empty($select_html) || false == $selectform) {
            /*允许发布文档的模型*/
            $allow_release_channel = !empty($allow_release_channel) ? $allow_release_channel : array('Article');

            /*所有栏目分类*/
            // $arctype_max_level = intval(config('global.arctype_max_level'));
            $arctype_max_level = 3;
            $where['c.status'] = 1;
            $fields = "c.id,c.status, c.pid, c.name,c.model, c.pids,count(s.id) as has_children, '' as children";

            $res = db('nav')
                ->field($fields)
                ->alias('c')
                ->join('__NAV__ s', 's.pid = c.id', 'LEFT')
                ->where($where)
                ->group('c.id')
                ->order('c.pid asc, c.sort asc, c.id')
//                ->cache(true, 100, "arctype")
                ->select();

            /*--end*/
            if (empty($res)) {
                return '';
            }

            /*所有栏目列表进行层次归类*/
            $arr = group_same_key($res, 'pid');

            for ($i = 0; $i < $arctype_max_level; $i++) {
                foreach ($arr as $key => $val) {
                    foreach ($arr[$key] as $key2 => $val2) {
                        if (!isset($arr[$val2['id']])) {
                            $arr[$key][$key2]['has_children'] = 0;
                            $arr[$key][$key2]['link'] = url(\request()->module() . '/' . $val2['model'] . '/index', ['navid' => $val2['id']]);
                            continue;
                        }
                        $val2['children'] = $arr[$val2['id']];
                        $arr[$key][$key2] = $val2;
                        $arr[$key][$key2]['link'] = url(\request()->module() . '/' . $val2['model'] . '/index', ['navid' => $val2['id']]);
                    }
                }
            }
            /*--end*/

            if (empty($arr[0])) {
                return '';
            }
            $nowArr = $arr[0];
//            dump($nowArr);
            return $nowArr;
//            return json_encode($nowArr);
        }
    }
}


if (!function_exists('nav_link')) {
    /**
     * 返回内部连接地址
     * @param $link
     * @return string
     */
    function nav_link($link)
    {
        $model = Request::instance()->module();
        switch ($model) {
            case 'mobile':
                $model = $model;
                break;
            case 'index':
                $model = $model;
                break;
            default:
                $model = 'index';
                break;
        }
        $d = $link;
        $dd = explode('-', $d);
        $ddd = json_encode($dd);
        $dddd = json_decode($ddd);

        if (stripos($link, "http") === 0) {
            $link = $link;
        } elseif ($dddd[0] == 'index' || !isset($dddd[1])) {
            $link = Request::instance()->domain();
        } else {
            $link = url($model . '/' . $dddd[0] . '/index', ['navid' => $dddd[1]]);
        }
        return $link;
    }
}

if (!function_exists('group_same_key')) {
    /**
     * 将二维数组以元素的某个值作为键，并归类数组
     *
     * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
     * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
     * @param $arr 数组
     * @param $key 分组值的key
     * @return array
     */
    function group_same_key($arr, $key)
    {
        $new_arr = array();
        foreach ($arr as $k => $v) {
            $new_arr[$v[$key]][] = $v;
        }
        return $new_arr;
    }
}


if (!function_exists('arctype_options')) {
    /**
     * 过滤和排序所有文章栏目，返回一个带有缩进级别的数组
     *
     * @param   int $id 上级栏目ID
     * @param   array $arr 含有所有栏目的数组
     * @param   string $id_alias id键名
     * @param   string $pid_alias 父id键名
     * @return  void
     */
    function arctype_options($spec_id, $arr, $id_alias, $pid_alias)
    {
        $cat_options = array();

        if (isset($cat_options[$spec_id])) {
            return $cat_options[$spec_id];
        }

        if (!isset($cat_options[0])) {
            $level = $last_id = 0;
            $options = $id_array = $level_array = array();
            while (!empty($arr)) {
                foreach ($arr AS $key => $value) {
                    $id = $value[$id_alias];
                    if ($level == 0 && $last_id == 0) {
                        if ($value[$pid_alias] > 0) {
                            break;
                        }

                        $options[$id] = $value;
                        $options[$id]['level'] = $level;
                        $options[$id][$id_alias] = $id;
                        // $options[$id]['typename']  = $value['typename'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0) {
                            continue;
                        }
                        $last_id = $id;
                        $id_array = array($id);
                        $level_array[$last_id] = ++$level;
                        continue;
                    }

                    if ($value[$pid_alias] == $last_id) {
                        $options[$id] = $value;
                        $options[$id]['level'] = $level;
                        $options[$id][$id_alias] = $id;
                        // $options[$id]['typename']  = $value['typename'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0) {
                            if (end($id_array) != $last_id) {
                                $id_array[] = $last_id;
                            }
                            $last_id = $id;
                            $id_array[] = $id;
                            $level_array[$last_id] = ++$level;
                        }
                    } elseif ($value[$pid_alias] > $last_id) {
                        break;
                    }
                }

                $count = count($id_array);
                if ($count > 1) {
                    $last_id = array_pop($id_array);
                } elseif ($count == 1) {
                    if ($last_id != end($id_array)) {
                        $last_id = end($id_array);
                    } else {
                        $level = 0;
                        $last_id = 0;
                        $id_array = array();
                        continue;
                    }
                }

                if ($last_id && isset($level_array[$last_id])) {
                    $level = $level_array[$last_id];
                } else {
                    $level = 0;
                    break;
                }
            }
            $cat_options[0] = $options;
        } else {
            $options = $cat_options[0];
        }

        if (!$spec_id) {
            return $options;
        } else {
            if (empty($options[$spec_id])) {
                return array();
            }

            $spec_id_level = $options[$spec_id]['level'];

            foreach ($options AS $key => $value) {
                if ($key != $spec_id) {
                    unset($options[$key]);
                } else {
                    break;
                }
            }

            $spec_id_array = array();
            foreach ($options AS $key => $value) {
                if (($spec_id_level == $value['level'] && $value[$id_alias] != $spec_id) ||
                    ($spec_id_level > $value['level'])) {
                    break;
                } else {
                    $spec_id_array[$key] = $value;
                }
            }
            $cat_options[$spec_id] = $spec_id_array;

            return $spec_id_array;
        }
    }
}


if (!function_exists('get_arr_column')) {
    /**
     * 获取数组中的某一列
     *
     * @param array $arr 数组
     * @param string $key_name 列名
     * @return array  返回那一列的数组
     */
    function get_arr_column($arr, $key_name)
    {
        $arr2 = array();
        foreach ($arr as $key => $val) {
            $arr2[] = $val[$key_name];
        }
        return $arr2;
    }
}
